import { Injectable } from '@nestjs/common';
import { CreateServiceDto } from './dto/create-service.dto';
import { UpdateServiceDto } from './dto/update-service.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Service } from './entities/service.entity';
import { Repository } from 'typeorm';
import { User } from '../user/entities/user.entity';
import { UserShopId } from '../user_shop-id/entities/user_shop-id.entity';

@Injectable()
export class ServiceService {
  constructor(
    @InjectRepository(Service)
    private readonly serviceRepository: Repository<Service>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(UserShopId)
    private readonly userShopRepository: Repository<UserShopId>,
  ) {}

  // 新增一个服务
  async create(createServiceDto: CreateServiceDto) {
    const shop = await this.userRepository.findOne({
      where: { id: createServiceDto.shopId },
    });
    const service = await this.serviceRepository.create(createServiceDto);

    service.shop = shop;
    return this.serviceRepository.save(service);
  }

  async skipFind(
    currentPage: number,
    pageSize: number,
    city: string,
    keywords?: string,
  ): Promise<Array<Service> | any> {
    let list = null;
    if (keywords) {
      list = await this.serviceRepository
        .createQueryBuilder('service')
        .leftJoinAndSelect('service.shop', 'shop')
        .where('shop.city = :city', { city: city })
        .andWhere('service.isDelete = :isDelete', { isDelete: false })
        .andWhere('car.license_plate LIKE :license_plate', {
          license_plate: `%${keywords}%`,
        })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    } else {
      list = await this.serviceRepository
        .createQueryBuilder('service')
        .leftJoinAndSelect('service.shop', 'shop')
        .where('shop.city = :city', { city: city })
        .andWhere('service.isDelete = :isDelete', { isDelete: false })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    }
    return {
      list: list[0],
      total: list[1],
      pageSize,
      currentPage,
      pages: Math.ceil(list[1] / pageSize),
    };
  }
  async findAll(): Promise<Array<Service | any>> {
    return this.serviceRepository.find();
  }

  // 查询单个
  async findOne(id: number): Promise<Service | any> {
    const res = await this.serviceRepository.findOne({
      relations: ['photos', 'shop'],
      where: { id },
    });

    const shopNameId = res.shopNameId;

    const shopNameInfo = await this.userShopRepository.findOne({
      where: { shopId: shopNameId },
    });

    return { ...res, shopName: shopNameInfo?.shopName || '暂无店铺信息' };
  }

  update(updateServiceDto: UpdateServiceDto) {
    const service = this.serviceRepository.create(updateServiceDto);
    return this.serviceRepository.save(service);
  }

  remove(ids: number[]) {
    ids.forEach(async (id) => {
      try {
        await this.serviceRepository
          .createQueryBuilder()
          .update(Service)
          .set({
            isDelete: true,
          })
          .where('id = :id', { id: id })
          .execute();
      } catch (e) {
        console.log('🚀 ~ This is a result of console.log ~ ✨: 删除失败', id);
      }
    });
    return;
  }
}
